package com.xie.o2o.service.impl;

import com.xie.o2o.cache.JedisUtil;
import com.xie.o2o.dao.ShopCategoryDao;
import com.xie.o2o.entity.ShopCategory;
import com.xie.o2o.service.ShopCategoryService;
import com.xie.o2o.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @create: xie
 */
@Service
public class ShopCategoryServiceImpl implements ShopCategoryService {
    @Autowired
    private ShopCategoryDao shopCategoryDao;
    @Autowired
    private JedisUtil.Keys jediskeys;
    @Autowired
    private JedisUtil.Strings jedisStrings;


    @Override
    public List<ShopCategory> getShopCategoryList(ShopCategory shopCategory) {
        //设置redis存储的key
        String key = SCLISTKEY;
        List<ShopCategory> shopCategoryList;
        String s;
        if (shopCategory == null) {
            //若查询条件为空，则列出所有一级分类,即parentid为空的
            key = key + "_allfirstlevel";
        } else if (shopCategory != null && shopCategory.getParent() != null && shopCategory.getParent().getShopCategoryId() != null) {
            //若parentid不为空，则列出其下所有子ID类别
            key = key + "_parent" + shopCategory.getParent().getShopCategoryId();
        } else if (shopCategory != null) {
            //列出所有类别，不管属于哪个类别
            key = key + "_allsecondlevel";
        }
        //判断key是否存在
        if (!jediskeys.exists(key)) {
            //不存在，从数据库获取
            shopCategoryList = shopCategoryDao.queryShopCategory(shopCategory);
            //转换成string
            s = JsonUtil.obj2String(shopCategoryList);
            //缓存在redis
            jedisStrings.set(key, s);
        } else {
            //key存在，从redis获取
            s = jedisStrings.get(key);
            //指定转换类型
            shopCategoryList = JsonUtil.string2Obj(s, ArrayList.class, ShopCategory.class);
        }
        return shopCategoryList;
    }
}
